package com.achun.getcouponleague.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.achun.getcouponleague.Bean.CacheWithDruration;
import com.achun.getcouponleague.Bean.Histories;
import com.achun.getcouponleague.base.BaseApplication;
import com.google.gson.Gson;

public class LocalHistoryUtil {
    public static LocalHistoryUtil localHisgoryUtil=null;
    public static final String DEFAULT_NAME="DEFAULT_NAME";

    private final SharedPreferences sharedPreferences;
    private final Gson gson;

    private LocalHistoryUtil(){
        sharedPreferences = BaseApplication.getAppContext().getSharedPreferences(DEFAULT_NAME, Context.MODE_PRIVATE);
        gson = new Gson();
    };
    public void saveCache(String key,Object value){
        this.saveCache(key,value,-1L);
    }
    //保存缓存
    public void saveCache(String key,Object value,long duration){
        SharedPreferences.Editor edit = sharedPreferences.edit();
        String valueStr = gson.toJson(value);
        if (duration!=-1) {
             duration = System.currentTimeMillis() + duration;
        }
        CacheWithDruration cacheWithDruration = new CacheWithDruration(duration, valueStr);
        String cacheWithDurationStr = gson.toJson(cacheWithDruration);
        edit.putString(key,cacheWithDurationStr);
        edit.apply();

    }
//    获取缓存
    public Histories getValue(String key, Class<Histories> clazz){
        String CacheStr = sharedPreferences.getString(key, null);
        if (CacheStr==null){
            return null;
        }
        CacheWithDruration cacheWithDruration = gson.fromJson(CacheStr, CacheWithDruration.class);
        long duration = cacheWithDruration.getDuration();
        if (duration!=-1&&duration-System.currentTimeMillis()<0){
            //过期了
                return null;
        }else {
//未过期
            String cache = cacheWithDruration.getCache();
            Histories result = gson.fromJson(cache, clazz);
            return result;
        }

    }
    //删除缓存
    public void deleteCache(String key){
    sharedPreferences.edit().remove(key).apply();
    }

    public static LocalHistoryUtil getInstance(){
        if (localHisgoryUtil==null){
            localHisgoryUtil=new LocalHistoryUtil();
        }
        return localHisgoryUtil;
    }


}
